package org.monkey.example.request.handler;


import cn.hutool.core.collection.CollUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.ReentrantLock;
import lombok.extern.slf4j.Slf4j;
import org.monkey.common.constant.config.CommonConstant;
import org.monkey.example.request.entity.convert.RequestInfoConvert;
import org.monkey.example.request.entity.form.RequestInfoAddForm;
import org.monkey.example.request.service.RequestInfoService;
import org.monkey.request.plugin.entity.RequestInfo;
import org.monkey.request.plugin.service.RequestLogAfterHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RequestLogSaveHandler implements RequestLogAfterHandler {

  public static ReentrantLock lock = new ReentrantLock();
  @Autowired
  RequestInfoService requestInfoService;
  @Autowired
  RequestInfoConvert requestInfoConvert;
  private int maxSize = 1000;


  private LinkedBlockingQueue<RequestInfo> queue = new LinkedBlockingQueue(2000);


  @Override
  public void doAfter(RequestInfo requestInfo) {
    //todo 请求日志处理逻辑
    queue.offer(requestInfo);
    int j = queue.size();
    if (j > maxSize) {
      requestSave();
    }
  }

  public void requestSave() {
    boolean f = lock.tryLock();
    if (f) {
      try {
        Collection<RequestInfo> coll = new ArrayList<>(queue.size());
        queue.drainTo(coll, queue.size());
        CommonConstant.ITEM_POOL.submit(() -> {
          saveBatch(coll);
        });
      } finally {
        lock.unlock();
      }
    }
  }

  private boolean saveBatch(Collection<RequestInfo> list) {
    if (CollUtil.isNotEmpty(list)) {
      for (RequestInfo ri : list) {
        RequestInfoAddForm ra = requestInfoConvert.convert2AddForm(ri);
        requestInfoService.add(ra);
      }
    }
    return true;
  }


}


